package com.example.buildtable.controller;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaJoinQueryWrapper;
import com.example.buildtable.pojo.Role;
import com.example.buildtable.pojo.User;
import com.example.common.util.R;
import com.example.buildtable.pojo.OperLog;
import com.example.buildtable.service.OperLogService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin
@RestController
@Tag(name = "操作日志")
@RequestMapping(value = "/operLog/")
public class OperLogController {
    @Autowired
    private OperLogService operLogService;
    
    @Operation(summary = "查询所有操作日志数据")
    @GetMapping(value = "/getAllOperLog")
    public R getAllOperLog() {
        LambdaJoinQueryWrapper<OperLog> wrapper = new LambdaJoinQueryWrapper<>(OperLog.class);
        wrapper.innerJoin(User.class, User::getUserId, OperLog::getOperUserId)
                .innerJoin(Role.class, Role::getRoleId, OperLog::getOperRoleId);
        List<OperLog> operLogList = operLogService.list(wrapper);
        return R.ok("查询所有操作日志数据成功").data("operLogList", operLogList);
    }
    
    @Operation(summary = "增加操作日志")
    @PostMapping(value = "/addOperLog")
    public R addOperLog(OperLog operLog) {
        boolean flag = operLogService.save(operLog);
        if (flag) {
            return R.ok("增加操作日志成功");
        } else {
            return R.ok("增加操作日志失败");
        }
    }

    @Operation(summary = "删除操作日志")
    @GetMapping(value = "/deleteOperLog/{operId}")
    public R deleteOperLog(@PathVariable("operId") Integer operId) {
        boolean flag = operLogService.removeById(operId);
        if (flag) {
            return R.ok("删除操作日志成功");
        } else {
            return R.ok("删除操作日志失败");
        }
    }

    @Operation(summary = "按照操作日志查看")
    @GetMapping(value = "/getOperLogById/{operId}")
    public R getOperLogById(@PathVariable("operId") Integer operId) {
        LambdaJoinQueryWrapper<OperLog> wrapper = new LambdaJoinQueryWrapper<>(OperLog.class);
        wrapper.innerJoin(User.class, User::getUserId, OperLog::getOperUserId)
                .innerJoin(Role.class, Role::getRoleId, OperLog::getOperRoleId);
        wrapper.eq(OperLog::getOperId, operId);
        OperLog operLog = operLogService.getOne(wrapper);
        if (operLog != null) {
            return R.ok("按照操作日志查看成功").data("operLog", operLog);
        } else {
            return R.error("按照操作日志查看失败");
        }
    }

    @Operation(summary = "修改操作日志")
    @PostMapping(value = "/updateOperLog")
    public R updateOperLog(OperLog operLog) {
        boolean flag = operLogService.updateById(operLog);
        if (flag) {
            return R.ok("修改操作日志成功");
        } else {
            return R.ok("修改操作日志失败");
        }
    }
}